package com.begye.smartloan.apptest.gongong

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.ext.toHaspMap
import com.begye.smartloan.apptest.ext.toJSONObjectList
import com.begye.smartloan.apptest.ext.toThousandUnitFormat
import com.begye.smartloan.apptest.tool.HttpLogInterceptor
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.doPostRequest
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class YongHuJiDingYiViewModel : ViewModel() {

    var decideJinE: Int = 0

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _sliderChangedLiveData = MutableLiveData<String>()
    val onSliderChangedLiveData get() = _sliderChangedLiveData

    private val _calChangedLiveData = MutableLiveData<JSONObject>()
    val onCalChangedLiveData get() = _calChangedLiveData

    private val _checkYongHuDataLiveData = MutableLiveData<JSONObject>()
    val onCheckYongHuDataLiveData get() = _checkYongHuDataLiveData

    private val _saveYongHuDataLiveData = MutableLiveData<Boolean>()
    val onSaveYongHuDataLiveData get() = _saveYongHuDataLiveData

    private val _shenQingSuccessfulDataLiveData = MutableLiveData<Boolean>()
    val onShenQingSuccessfulDataLiveData get() = _shenQingSuccessfulDataLiveData

    private val _anaDataFinishedDataLiveData = MutableLiveData<Boolean>()
    val onAnaDataFinishedDataLiveData get() = _anaDataFinishedDataLiveData

    private val _checkRecordsDataLiveData = MutableLiveData<List<JSONObject>>()
    val onCheckRecordsDataLiveData get() = _checkRecordsDataLiveData

    private val _checkHuanKuanListDataLiveData = MutableLiveData<List<JSONObject>>()
    val onCheckHuanKuanListDataLiveData get() = _checkHuanKuanListDataLiveData

    private val _huanKuanUrlLiveData = MutableLiveData<JSONObject>()
    val onHuanKuanUrlLiveData get() = _huanKuanUrlLiveData

    private val _pinStatusLiveData = MutableLiveData<JSONObject>()
    val onPinStatusLiveData get() = _pinStatusLiveData

    fun isDidCertify(): Boolean {
        return _checkYongHuDataLiveData.value?.run {
            optString("certify") == "YES"
        } ?: false
    }

    fun businessTypes(): JSONArray {
        val values = JSONArray().apply {
            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_18))
                put("value", MyApplication.context.getString(R.string.certification_text_18))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_19))
                put("value", MyApplication.context.getString(R.string.certification_text_19))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_20))
                put("value", MyApplication.context.getString(R.string.certification_text_20))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_21))
                put("value", MyApplication.context.getString(R.string.certification_text_21))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_22))
                put("value", MyApplication.context.getString(R.string.certification_text_22))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_23))
                put("value", MyApplication.context.getString(R.string.certification_text_23))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_24))
                put("value", MyApplication.context.getString(R.string.certification_text_24))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_25))
                put("value", MyApplication.context.getString(R.string.certification_text_25))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_26))
                put("value", MyApplication.context.getString(R.string.certification_text_26))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_27))
                put("value", MyApplication.context.getString(R.string.certification_text_27))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_28))
                put("value", MyApplication.context.getString(R.string.certification_text_28))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_29))
                put("value", MyApplication.context.getString(R.string.certification_text_29))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_30))
                put("value", MyApplication.context.getString(R.string.certification_text_30))
            })

            put(JSONObject().apply {
                put("title", MyApplication.context.getString(R.string.certification_text_31))
                put("value", MyApplication.context.getString(R.string.certification_text_31))
            })
        }
        return values
    }

    fun salaryDays(): JSONArray {
        val values = JSONArray()
        for (index in 1 until 29) {
            val day = index.toString()
            values.apply {
                put(JSONObject().apply {
                    put("title", day)
                    put("value", day)
                })
            }
        }
        return values
    }

    fun calSliderChanged(process: Float, isSliding: Boolean = true) {
        try {
            _checkYongHuDataLiveData.value?.let { result ->
                println(result)
                var minJinE = result.optString("minJinE", "0")
                val remainJinEInt = result.optInt("remainJinEInt", 0)

                if (minJinE.isBlank()) {
                    minJinE = "0"
                }
                val jinE = minJinE.toFloat()

                // ke li du
                val granularity = SysConfigTool.filterStepJinE().toInt()

                val edgeJinE = remainJinEInt.toFloat() - minJinE.toFloat()
                val needAddJinE = (edgeJinE * process / 100F).toInt()
                val scale = (((jinE + needAddJinE) / granularity).toInt()) * granularity
                val resultJinEFormat = scale.toString().toThousandUnitFormat()

                decideJinE = scale
                _sliderChangedLiveData.value = resultJinEFormat

                if (isSliding) return
                if (decideJinE > 0) {
                    val decideJson = JSONObject()
                    val disJinE = decideJinE.toString().toThousandUnitFormat()
                    decideJson.put("disJinE", disJinE)
                    decideJson.put("disWithJinE", disJinE)
                    decideJson.put("disFee", "0")

                    var pDay = result.optString("pDay", "1")
                    if (pDay.isBlank()) {
                        pDay = "1"
                    }
                    val pDayInt = pDay.toInt()
                    val edgeDays = daysUntilNextMonth(pDayInt)
                    val rpFee = (decideJinE * 0.08F / 100 * edgeDays).toInt()
                    val rpJinE = (decideJinE + rpFee)

                    decideJson.put("rpJinE", rpJinE.toString().toThousandUnitFormat())
                    decideJson.put("rpWithJinE", disJinE)
                    decideJson.put("rpFee", rpFee.toString().toThousandUnitFormat())

                    _calChangedLiveData.value = decideJson

                } else {
                    val decideJson = JSONObject()
                    decideJson.put("disJinE", "0")
                    decideJson.put("disWithJinE", "0")
                    decideJson.put("disFee", "0")

                    decideJson.put("rpJinE", "0")
                    decideJson.put("rpWithJinE", "0")
                    decideJson.put("rpFee", "0")

                    _calChangedLiveData.value = decideJson
                }

            }
        } catch (e: Exception) {
            //
            e.printStackTrace()
        }
    }

    private fun daysUntilNextMonth(targetDay: Int): Long {
        val today = Calendar.getInstance()

        // 设置为下个月的指定日期
        val nextMonthDate = Calendar.getInstance().apply {
            add(Calendar.MONTH, 1)
            set(Calendar.DAY_OF_MONTH, targetDay)
        }

        // 计算两者之间的毫秒差并转换为天数
        val diffInMillis = nextMonthDate.timeInMillis - today.timeInMillis
        return diffInMillis / (1000 * 60 * 60 * 24)
    }

    private fun currentMonthDate(): String {
        val nextMonthDate = Date()
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return dateFormat.format(nextMonthDate.time)
    }

    private fun getNextMonthDate(targetDay: Int): String {
        val nextMonthDate = Calendar.getInstance().apply {
            add(Calendar.MONTH, 1)               // 设置为下个月
            set(Calendar.DAY_OF_MONTH, targetDay) // 设置为指定天
        }

        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return dateFormat.format(nextMonthDate.time)
    }

    fun calculateDaysBetweenDates(startDate: String, endDate: String): Long {
        try {
            // 定义日期格式
            val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

            // 将字符串解析为 Date 对象
            val start = dateFormat.parse(startDate)
            val end = dateFormat.parse(endDate)

            return if ((start != null) and (end != null)) {
                // 使用 Calendar 计算天数差
                val diffInMillis = end!!.time - start!!.time
                diffInMillis / (1000 * 60 * 60 * 24)
            } else {
                0L
            }
        } catch (e: Exception) {
            return 0L
        }
    }

    fun daysBetween(dateString: String): Long {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        // 解析目标日期
        val targetDate = Calendar.getInstance().apply {
            time = dateFormat.parse(dateString) ?: return 0L // 若解析失败则返回 0
        }

        // 获取当前日期
        val today = Calendar.getInstance()

        // 计算两者之间的毫秒差并转换为天数
        val diffInMillis = targetDate.timeInMillis - today.timeInMillis
        return TimeUnit.MILLISECONDS.toDays(diffInMillis)
    }

    fun currentDay(): Int {
        val calendar = Calendar.getInstance()
        return calendar.get(Calendar.DAY_OF_MONTH) // 获取当前日期
    }

    fun daysInCurrentMonth(): Int {
        val calendar = Calendar.getInstance()
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH) // 获取当月的总天数
    }

    fun requestYongHuJiDingYi() {
        doPostRequest(
            "/ge434ve23Usfjataiinseo",
            hashMapOf(),
            _loadingStateLiveData,
            object : IApiProcessCallback {
                override fun onApiReady() {
                    if (_loadingStateLiveData.value != true) {
                        _loadingStateLiveData.value = true
                    }
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        _loadingStateLiveData.value = false
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val uJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val certify = uJson.optString("certify", "NO")
                        LoginTool.didCertify = certify == "YES"

                        // used jin e
                        var usedJinEInt = 0
                        val list = uJson.optJSONArray("list") ?: JSONArray()
                        for (index in 0 until list.length()) {
                            val pItem = list.optJSONObject(index)
                            if (pItem != null) {
                                val pStatus = pItem.optString("status", "")
                                val isValidStatus = (pStatus == "RP") or (pStatus == "RV")
                                if (isValidStatus) {
                                    var pJinE = pItem.optString("jinE", "0")
                                    if (pJinE.isBlank()) {
                                        pJinE = "0"
                                    }
                                    val pJinEInt = pJinE.toInt()
                                    usedJinEInt += pJinEInt
                                }
                            }
                        }

                        uJson.apply {
                            put("usedJinEInt", usedJinEInt)
                            put("usedJinEFormat", usedJinEInt.toString().toThousandUnitFormat())
                        }

                        var pDay = uJson.optString("pDay", "1")
                        if (pDay.isBlank()) {
                            pDay = "1"
                        }
                        val pDayInt = pDay.toInt()
                        val nextPDate = getNextMonthDate(pDayInt)
                        uJson.apply {
                            put("nextPDate", nextPDate)
                        }

                        var maxJinE = uJson.optString("maxJinE", "0")
                        var minJinE = uJson.optString("minJinE", "0")

                        if (maxJinE.isBlank()) {
                            maxJinE = "0"
                        }

                        if (minJinE.isBlank()) {
                            minJinE = "0"
                        }

                        // 首页最大金额 = {(当前天 - 发资天) 的绝对值 + 1} 乘以 {每天的工资}
                        val curDay = currentDay()
                        val monthDays = daysInCurrentMonth()
                        val maxJinEInt = maxJinE.toInt()
                        val everyDayJinE = maxJinEInt / monthDays
                        var maxJinERealInt = everyDayJinE * (abs(curDay - pDayInt) + 1)
                        // 以step jin e为单位
                        val stepJinE = SysConfigTool.filterStepJinE().toInt()
                        maxJinERealInt = (maxJinERealInt / stepJinE) * stepJinE

                        // 剩余可借金额，即首页额度
                        var remainJinEInt = maxJinERealInt - usedJinEInt
                        remainJinEInt = (remainJinEInt / stepJinE) * stepJinE
                        if (remainJinEInt < 0) {
                            remainJinEInt = 0
                        }

                        uJson.apply {
                            put(
                                "maxJinERealFormat",
                                maxJinERealInt.toString().toThousandUnitFormat()
                            )
                            put("remainJinEFormat", remainJinEInt.toString().toThousandUnitFormat())
                            put("maxJinEFormat", maxJinE.toThousandUnitFormat())
                            put("minJinEFormat", minJinE.toThousandUnitFormat())
                        }

                        uJson.apply {
                            put("maxJinERealInt", maxJinERealInt)
                            put("remainJinEInt", remainJinEInt)
                            put("maxJinEInt", maxJinE.toInt())
                            put("minJinEInt", minJinE.toInt())
                        }

                        uJson.apply {
                            put("maxJinERealInt", maxJinERealInt)
                        }

                        // slide jin e
                        val sliderJinEInt = remainJinEInt / 2
                        uJson.apply {
                            put("sliderJinEInt", sliderJinEInt)
                            put("sliderJinEFormat", sliderJinEInt.toString())
                        }
                        decideJinE = sliderJinEInt

                        // 输出
                        HttpLogInterceptor.printJson(uJson)

                        // finish
                        _checkYongHuDataLiveData.value = uJson

                        if (decideJinE > 0) {
                            val decideJson = JSONObject()
                            val disJinE = decideJinE.toString().toThousandUnitFormat()
                            decideJson.put("disJinE", disJinE)
                            decideJson.put("disWithJinE", disJinE)
                            decideJson.put("disFee", "0")

                            val edgeDays = daysUntilNextMonth(pDayInt)
                            val rpFee = (decideJinE * 0.08F / 100 * edgeDays).toInt()
                            val rpJinE = (decideJinE + rpFee)

                            decideJson.put("rpJinE", rpJinE.toString().toThousandUnitFormat())
                            decideJson.put("rpWithJinE", disJinE)
                            decideJson.put("rpFee", rpFee.toString().toThousandUnitFormat())

                            _calChangedLiveData.value = decideJson

                        } else {
                            val decideJson = JSONObject()
                            decideJson.put("disJinE", "0")
                            decideJson.put("disWithJinE", "0")
                            decideJson.put("disFee", "0")

                            decideJson.put("rpJinE", "0")
                            decideJson.put("rpWithJinE", "0")
                            decideJson.put("rpFee", "0")

                            _calChangedLiveData.value = decideJson
                        }

                    } catch (e: Exception) {
                        //
                        _loadingStateLiveData.value = false
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                    _loadingStateLiveData.value = false
                }
            })
    }

    fun requestYongHuJiDingYiForRecords() {
        doPostRequest(
            path = "/ge434ve23Usfjataiinseo",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {

                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val uJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val certify = uJson.optString("certify", "NO")
                        LoginTool.didCertify = certify == "YES"

                        val array = uJson.optJSONArray("list") ?: JSONArray()
                        val list = array.toJSONObjectList()
                        _checkRecordsDataLiveData.value = list

                    } catch (e: Exception) {
                        //
                        e.printStackTrace()
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestYongHuJiDingYiForHuanKuan() {
        doPostRequest(
            path = "/ge434ve23Usfjataiinseo",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {

                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        _loadingStateLiveData.value = false
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val uJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val certify = uJson.optString("certify", "NO")
                        LoginTool.didCertify = certify == "YES"

                        val array = uJson.optJSONArray("list") ?: JSONArray()
                        val list = array.toJSONObjectList()
                        _checkHuanKuanListDataLiveData.value = list.filter {
                            val status = it.optString("status")
                            if (status == "RP") {
                                val aDate = currentMonthDate()
                                val pDate = it.optString("pDate")
                                val daysBetween = calculateDaysBetweenDates(aDate, pDate)
                                it.put("daysLeft", daysBetween)

                                var overDay = it.optString("overDay", "")
                                if (overDay.isBlank()) {
                                    overDay = "0"
                                }
                                if (daysBetween < 0) {
                                    overDay = abs(daysBetween).toString()
                                }

                                it.put("overDay", overDay)
                                it.put("overJinE", "0")

                                if (daysBetween < 0) {
                                    val jinEF = it.optString("jinE").toFloat()
                                    val overJinE = (jinEF * 0.002 * daysBetween * (-1F)).toInt()

                                    var totalP = it.optString("totalP").toInt()
                                    totalP += overJinE

                                    it.put("totalP", totalP.toString())
                                    it.put("overJinE", overJinE.toString())
                                }

                                true
                            } else false
                        }

                    } catch (e: Exception) {
                        //
                        e.printStackTrace()
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }

    fun requestYongHuJiDingYiForHuanKuanPinStatus() {
        doPostRequest(
            path = "/ge434ve23Usfjataiinseo",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val uJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val certify = uJson.optString("certify", "NO")
                        LoginTool.didCertify = certify == "YES"

                        _pinStatusLiveData.value = uJson

                    } catch (e: Exception) {
                        //
                        e.printStackTrace()
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestYongHuJiDingYiForHuanKuanPinUrl() {
        doPostRequest(
            path = "/ge434ve23Usfjataiinseo",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val uJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val certify = uJson.optString("certify", "NO")
                        LoginTool.didCertify = certify == "YES"

                        _huanKuanUrlLiveData.value = uJson

                    } catch (e: Exception) {
                        //
                        e.printStackTrace()
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestSaveYongHuJiDingYi(
        companyName: String,
        businessType: String,
        companyAddress: String,
        salary: String,
        pDate: String,
        salaryUrls: String,
        selfieUrls: String
    ) {
        val sourceJson = _checkYongHuDataLiveData.value ?: return
        val paramsJson = JSONObject(sourceJson.toString())
        paramsJson.apply {
            put("certify", "YES")
            put("pDay", pDate)
            put("maxJinE", salary)
            put("usedJinE", "0")
            put("certifyInfo", JSONObject().apply {
                put("companyName", companyName)
                put("businessType", businessType)
                put("companyAddress", companyAddress)
                put("salary", salary)
                put("pDay", pDate)
                put("salaryUrls", salaryUrls)
                put("selfieUrls", selfieUrls)
            })
        }

        var maxJinE = paramsJson.optString("maxJinE", "0")
        var minJinE = paramsJson.optString("minJinE", "0")

        if (maxJinE.isBlank()) {
            maxJinE = "0"
        }

        if (minJinE.isBlank()) {
            minJinE = "0"
        }

        paramsJson.apply {
            put("maxJinEFormat", maxJinE.toThousandUnitFormat())
            put("minJinEFormat", minJinE.toThousandUnitFormat())
        }

        paramsJson.apply {
            put("maxJinEInt", maxJinE.toInt())
            put("minJinEInt", minJinE.toInt())
        }

        val resultJson = JSONObject().apply {
            put("userInfo", paramsJson)
        }

        val params = resultJson.toHaspMap()
        println(resultJson)

        doPostRequest(
            path = "/sa434ve232AbsfjaUsdfio",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()

                        // finish
                        _saveYongHuDataLiveData.value = true

                    } catch (e: Exception) {
                        //
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestSaveShenQing() {
        val sourceJson = _checkYongHuDataLiveData.value ?: return
        val paramsJson = JSONObject(sourceJson.toString())

        val list = paramsJson.optJSONArray("list") ?: JSONArray()
        var usedJinE = decideJinE
        for (index in 0 until list.length()) {
            val item = list.optJSONObject(index)
            if (item != null) {
                val status = item.optString("status", "")
                if ((status == "RP") or (status == "RV")) {
                    val jinEInt = item.optString("jinE", "0").toInt()
                    usedJinE += jinEInt
                }
            }
        }

        var pDay = paramsJson.optString("pDay", "1")
        if (pDay.isBlank()) {
            pDay = "1"
        }
        val pDayInt = pDay.toInt()
        val edgeDays = daysUntilNextMonth(pDayInt)
        val rpFee = (decideJinE * 0.08F / 100 * edgeDays).toInt()
        val rpJinE = (decideJinE + rpFee)
        val nextPDate = getNextMonthDate(pDayInt)
        val nextADate = currentMonthDate()

        val rpItem = JSONObject().apply {
            put("totalP", rpJinE.toString())
            put("pDate", nextPDate)
            put("aDate", nextADate)
            put("jinE", decideJinE.toString())
            put("fee", rpFee.toString())
            put("overDay", "")
            put("overJinE", "")
            put("status", "RP")
        }
        list.put(rpItem)

        paramsJson.apply {
            put("list", list)
            put("usedJinE", usedJinE.toString())
        }

        val resultJson = JSONObject().apply {
            put("userInfo", paramsJson)
        }

        val params = resultJson.toHaspMap()
        println(resultJson)

        doPostRequest(
            path = "/sa434ve232AbsfjaUsdfio",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()

                        // finish
                        _shenQingSuccessfulDataLiveData.value = true

                    } catch (e: Exception) {
                        //
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestSaveDataAnlFinished() {
        doPostRequest(
            path = "/ge434ve23Usfjataiinseo",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val uInfo = obj.optString("userInfo", "")

                        val paramsJson = if (uInfo.isBlank()) {
                            JSONObject(
                                mapOf(
                                    "certify" to "NO",
                                    "maxJinE" to "0",
                                    "minJinE" to "0",
                                    "nextPDate" to "",
                                    "usedJinE" to "0",
                                    "pDay" to "1",
                                    "list" to JSONArray()
                                )
                            )
                        } else {
                            JSONObject(uInfo)
                        }

                        val list = paramsJson.optJSONArray("list") ?: JSONArray()
                        for (index in 0 until list.length()) {
                            val item = list.optJSONObject(index)
                            if (item != null) {
                                val status = item.optString("status", "")
                                if (status == "RV") {
                                    item.put("status", "RP")
                                }
                            }
                        }

                        paramsJson.apply {
                            put("list", list)
                        }

                        val resultJson = JSONObject().apply {
                            put("userInfo", paramsJson)
                        }

                        val params = resultJson.toHaspMap()
                        println(resultJson)

                        doPostRequest(
                            path = "/sa434ve232AbsfjaUsdfio",
                            action = params,
                            loading = _loadingStateLiveData,
                            callback = object : IApiProcessCallback {
                                override fun onApiReady() {
                                }

                                override fun onApiDone(jsonObject: JSONObject) {
                                    try {
                                        // finish
                                        _anaDataFinishedDataLiveData.value = true

                                    } catch (e: Exception) {
                                        //
                                    }
                                }

                                override fun onApiError(code: String, errMsg: String) {
                                }

                            })

                    } catch (e: Exception) {
                        //
                        e.printStackTrace()
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }
            })
    }

}